package com.zhou.framework.filter;

import com.zhou.framework.config.SystemConfig;
import com.zhou.framework.exception.VerifyException;
import com.zhou.framework.model.RS;
import com.zhou.util.IpUtils;
import com.zhou.util.WebUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Slf4j
public class CommonFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        boolean frameCheck = SystemConfig.getInstance().isXFrameOptions();
        boolean refererCheck = SystemConfig.getInstance().isRefererCheck();
        if(frameCheck){
            //禁止嵌入iframe
            response.addHeader("X-Frame-Options","SAMEORIGIN");
        }
        if(refererCheck){
            //检查请求头referer
            String referer = request.getHeader("referer");
            if (referer != null && !referer.contains(request.getServerName())) {
                log.warn("referer：{}. serverName：{}",referer,request.getServerName());
                //如果 链接地址来自其他网站，则返回错误页面
                WebUtil.writeObject(response, RS.failed("referer deny"));
                return;
            }
        }
        response.addHeader("Content-Security-Policy","img-src 'self' data:; default-src 'self' 'unsafe-hashes' 'unsafe-inline'");
        String ip = WebUtil.getIp(request);
        if(!IpUtils.isIp(ip)){
            throw new VerifyException("ip错误");
        }
        chain.doFilter(request, response);
    }
}
